package com.yyr.spring_boot.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@WebFilter
public class ParamFilter implements Filter {

    public static final Logger LOGGER = LoggerFactory.getLogger(ParamFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.debug("==== Init filter ====");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        LOGGER.debug("==== Do filter ====");
        // 将 ServletRequest 等转化为 HttpServletRequest 等
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 因为 HttpServletRequest 不能直接操作 parameterMap，所以构建 Wrapper 对象类进项操作
        HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) {

            // 重写 wrapper 对象的 getParameter 方法，替换掉脏字符串
            @Override
            public String getParameter(String name) {
                String value = super.getParameter(name);

                return StringUtils.isNoneBlank(value) ?
                        value.replaceAll("fuck", "***") : "";
            }

            @Override
            public String[] getParameterValues(String name) {
                String[] values = super.getParameterValues(name);
                if (values == null) {
                    return new String[]{};
                }
                return Arrays.asList(values)
                        .stream()
                        .map(item -> item.replaceAll("fuck", "***"))
                        .toArray(String[]::new);
            }
        };

        // 将 wrapper 和response 对象交出去
        filterChain.doFilter(wrapper,servletResponse);
    }

    @Override
    public void destroy() {
        LOGGER.debug("==== Destroy filter ====");
    }
}
